﻿using System;
using System.Xml.Serialization;
using System.Web.Script.Serialization;

using Fuse8.DomainFramework.Domain;
using Fuse8.DomainFramework.BusinessService;
using Fuse8.DomainFramework.CacheService;
using Fuse8.ContentManagementFramework.Domain.Bases;

namespace Fuse8.ContentManagementFramework.Domain
{
    [Serializable]
    public abstract class CmsSiteEntityObject : CmsTrackingEntityObject, ISiteAwareEntityObject
    {
        #region Fields

        [NonSerialized]
        private SiteAwareCategory _category = SiteAwareCategory.NotDefined;

        #endregion

        #region Linked fields

        private CmsSite _site;

        private CmsSiteGroup _siteGroup;

        #endregion

        #region Properties

        public virtual int? SiteGroupId { get; set; }

        public virtual int? SiteId { get; set; }

        public SiteAwareCategory SiteCategory
        {
            get
            {
                if (_category == SiteAwareCategory.NotDefined)
                {
                    _category = this.GetCategory();
                }

                return _category;
            }
            set
            {
                _category = value;
            }
        }

        #endregion

        #region Linked properties

        [XmlIgnore]
        [ScriptIgnore]
        public CmsSite Site
        {
            get
            {
                if (_site == null)
                {
                    if (SiteId.HasValue && SiteId != 0)
                    {
                        var businessFacade = new BusinessServiceFacade<CmsSite, int>();
                        if (businessFacade != null)
                        {
                            _site = businessFacade.FindOne(SiteId.GetValueOrDefault(0));
                        }
                    }
                }
                return _site;
            }
            set
            {
                SiteId = value != null ? value.Id : new Nullable<int>();

                _site = null;
            }
        }

        [XmlIgnore]
        [ScriptIgnore]
        public CmsSiteGroup SiteGroup
        {
            get
            {
                if (_siteGroup == null)
                {
                    if (SiteGroupId.HasValue && SiteGroupId != 0)
                    {
                        var businessFacade = new BusinessServiceFacade<CmsSiteGroup, int>();
                        if (businessFacade != null)
                        {
                            _siteGroup = businessFacade.FindOne(SiteGroupId.GetValueOrDefault(0));
                        }
                    }
                }
                return _siteGroup;
            }
            set
            {
                SiteGroupId = value != null ? value.Id : 0;

                _siteGroup = null;
            }
        }

        #endregion
    }
}
